package com.foreknow.spring;

import com.xianzhi.bean.Admin;
import com.foreknow.service.AdminServiceImpl;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * IOC容器
 */

public class ClassPathXmlApplicationContext implements BeanFatory{
//    创建一个容器
    private Map<String,Object> beans = new HashMap<>();
    public ClassPathXmlApplicationContext() throws JDOMException, IOException, ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        //创建一个解析器
        SAXBuilder builder = new SAXBuilder();
//        构造文档
        Document document = builder.build(this.getClass().getClassLoader().getResourceAsStream("beans.xml"));
         //获取到根节点
        Element root = document.getRootElement();
        //获取到子节点
        List<Element> list = root.getChildren();
        for(int i=0;i<list.size();i++){
            Element element = list.get(i);
            //获取到id的值
            String id = element.getAttributeValue("id");
            String clazz = element.getAttributeValue("class");
            System.out.println(id);
            System.out.println(clazz);
            // .newInstance 实例化为对象
            Object o = Class.forName(clazz).newInstance();
            //要将获取到的对象保存到Map容器中
            beans.put(id,o);
            List<Element> children = element.getChildren();
            for(Element prop :children){
                String name = prop.getAttributeValue("name");
                String bean = prop.getAttributeValue("bean");
                //从map中获取到所对应的对象(AdminDaoImpl对象)
                Object beanObject = beans.get(bean);
                //模拟拼接一个方法 setAdminDao
                String methodName = "set"+name.substring(0,1).toUpperCase()+name.substring(1);
                //获取AdminService到对象中的方法名 后期可以使用invoke调用改方法
                //o 指向的是AdminService,获取到adminDaoImpl对象的 接口
                Method method = o.getClass().getMethod(methodName, beanObject.getClass().getInterfaces());
                //调用method中的invoke方法来调用setAdminDao方法
                //第一个参数是要职向的AdminService对象
                method.invoke(o,beanObject);
            }
        }
    }
    @Override
    public Object getBean(String id) {
        return null;
    }

    public static void main(String[] args) throws JDOMException, IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
            BeanFatory beanFatory = new ClassPathXmlApplicationContext();
            AdminServiceImpl service = (AdminServiceImpl) beanFatory.getBean("adminService");
            service.save(new Admin());
    }

}
